<template>
    <el-dialog v-model="selectKnowVisible" :width="width" class="custom-dialog select-know-dialog" :show-close='false'
        :close-on-click-modal="modalClose" modal-class="dialog-center" :before-close="handleClose">
        <div class="select-know-header">
            <div class="title-tips">
                <div class="title">{{ props.title || $t('message.text.createDoc') }}</div>
                <div class="tips">{{ $t('message.text.checkLibrary') }}</div>
            </div>
            <svg class="close-icon" @click="handleClose">
                <use xlink:href="#keowledge-danchuangguanbi1"></use>
            </svg>
        </div>
        <div class="select-know-body">
            <div class="know-search-box">
                <svg class="search-icon">
                    <use xlink:href="#keowledge-sousuo"></use>
                </svg>
                <el-input v-model="searchVal" :placeholder="$t('message.placeholder.librarySearch')"></el-input>
                <svg class="clear-icon" @click="clearSearchVal">
                    <use v-bind:xlink:href="`#${searchVal ? 'keowledge-danchuangguanbi' : ''}`"></use>
                </svg>
            </div>
            <div class="know-tree-box" v-loading="treeLoading">
                <el-scrollbar v-if="treeData.length != 0">
                    <el-tree :data="treeData" node-key="id" ref="elTreeRef" :expand-on-click-node="false"
                        @node-click="handleNodeClick" :filter-node-method="treeilter"
                        :props='{ children: "children", label: "name" }'>
                        <template #default="{ node, data }">
                            <span class="custom-tree-node" :class="[isArrow(data) && 'file-node', isArrow(data) && !data.isLoad && 'arrow-node',
                            checkedFileItem.id == data.id && 'custom-tree-node-active']">
                                <svg class="file-icon">
                                    <use v-bind:xlink:href="`${getIcon(data.type, data.nameSuffix)}`"></use>
                                </svg>
                                <span class="label-content" :style="{ width: `calc(280px - ${data.level * 24}px)` }"
                                    v-tooltip-auto-show>
                                    <el-tooltip :content="node.label" effect="light">
                                        <div class="label">{{ node.label }}</div>
                                    </el-tooltip>
                                </span>
                                <div class="custom-tree-arrow-box" v-if="isArrow(data) && !data.isLoad"></div>
                                <el-icon class="circular custo-tree-loading"
                                    :style="{ right: `calc(-14px - ${data.level * 4}px)` }" v-if="data.loading">
                                    <Loading />
                                </el-icon>
                            </span>
                        </template>
                    </el-tree>
                </el-scrollbar>
                <jvs-empty v-if="treeData.length == 0"></jvs-empty>
            </div>
        </div>
        <template #footer>
            <div class="know-footer">
                <el-button @click="handleClose">{{ $t('message.buttons.cancal') }}</el-button>
                <el-button type="primary" :disabled="!checkedFileItem.id" @click="handleSave">
                    {{ $t('message.buttons.submit') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    nextTick,
    getCurrentInstance
} from 'vue'
import { getFileMenuTree, getDcLibraryList, getLibTree } from '@/api/knowledge'
import { getTemplateReplace } from '@/api/template'
import { useRouter } from "vue-router"
import { useHookI18n } from '@/hooks/i18n'

const { locale, $t } = useHookI18n()
const router = useRouter();

const emit = defineEmits(["callBack", 'close'])
const props = defineProps({
    width: {
        type: String,
        default: '416px'
    },
    remove: Function,
    callBack: Function,
    title: {
        type: String,
        default: ''
    },
    modalClose: {
        type: Boolean,
        default: false
    },
    isTemplate: {
        type: Boolean,
        default: false
    },
    selectKnowType: {
        type: String,
        default: 'folder'
    },
    checkFileType: {
        type: [String, Array],
    }
})
//const { } = toRefs(props);
const searchVal = ref('')
const { } = toRefs(
    reactive({
        //定义数组和对象
    })
);
const treeData = ref([])
const selectKnowVisible = ref(false)
const treeLoading = ref(false)
const checkedFileItem = ref({
    id: ''
})
const elTreeRef = ref()

function init() {
    selectKnowVisible.value = true
    treeLoading.value = true
    let fun: any
    if (props.selectKnowType == 'folder') {
        fun = getFileMenuTree
        if (props.isTemplate) {
            fun = getTemplateReplace
        }
    } else {
        fun = getDcLibraryList
    }
    fun({
        sieze: 1000,
        current: 1
    }).then(res => {
        if (res.data.code == 0) {
            if (props.selectKnowType == 'folder') {
                treeData.value = res.data.data || []
            } else {
                treeData.value = res.data.data.records || []
                treeData.value.forEach((item) => {
                    item.level = 0
                })
            }
            treeLoading.value = false
        }
    }).catch(err => {
        treeLoading.value = false
    })
}

function isArrow(data) {
    if (props.selectKnowType == 'file') {
        if (data.parentId == '0' || ['knowledge', 'directory'].includes(data.type)) {
            return true
        } else {
            return false
        }
    }
    return false
}

function handleClose() {
    searchVal.value = ''
    checkedFileItem.value = {
        id: ''
    }
    treeData.value = []
    selectKnowVisible.value = false
    emit("close")
}

function clearSearchVal() {
    searchVal.value = ''
}

watch(searchVal, (val) => {
    elTreeRef.value!.filter(val)
})

interface Tree {
    [key: string]: any
}

function treeilter(value: string, data: Tree) {
    if (!value) return true
    if (data.type == 'knowledge') {
        return data.name.includes(value)
    } else {
        return false
    }
}

function handleNodeClick(data: any, node: any) {
    if (props.selectKnowType == 'folder') {
        checkedFileItem.value = data
    } else {
        if (['knowledge', "directory"].includes(data.type)) {
            if (data.isLoad) return
            data.loading = true
            getLibTree({
                id: data.id
            }).then(res => {
                if (res.data.code == 0) {
                    const arr = res.data.data.data.filter(item => props.checkFileType?.includes(item.nameSuffix) || item.type == 'directory')
                    arr.forEach((item) => {
                        item.level = data.level + 1
                    })
                    data.children = arr
                    data.isLoad = true
                    node.expanded = true
                }
                data.loading = false
            }).catch((err) => {
                data.loading = false
            })
        } else {
            checkedFileItem.value = data
        }
    }
}

function handleSave() {
    emit('callBack', checkedFileItem.value)
    handleClose()
}

defineExpose({
    init
})
</script>
<style lang="scss">
.select-know-dialog {
    width: 416px !important;

    .select-know-header {
        height: 56px;
        background: #F5F6F7;
        padding: 0px 16px 0px 24px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title-tips {
            .title {
                @include SourceHanSansCN-Bold;
                font-size: 14px;
                color: #363b4c;
                margin-bottom: 2px;
            }

            .tips {
                font-size: 12px;
                color: #6f7588;
                @include SourceHanSansCN-Regular;
            }
        }

        .close-icon {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }
    }

    .select-know-body {
        padding: 0px 32px 8px;

        .know-search-box {
            margin-top: 16px;
            display: flex;
            align-items: center;
            height: 32px;
            background-color: #F5F6F7;
            border-radius: 4px;
            padding: 0px 14px;
            box-sizing: border-box;
            margin-bottom: 8px;

            .search-icon {
                width: 16px;
                height: 16px;
            }

            .clear-icon {
                width: 16px;
                height: 16px;
                cursor: pointer;
            }

            .el-input {
                height: 30px !important;
                width: 100% !important;
            }

            .el-input__inner {
                height: 30px !important;
                line-height: 30px !important;
                border: none !important;
                background-color: transparent !important;
                padding: 0px !important;
            }

            .el-input__wrapper {
                width: 100% !important;
                background-color: transparent !important;
                box-shadow: none !important;
            }
        }

        .know-tree-box {
            height: 364px;
            overflow-y: auto;

            .el-tree-node {
                border-bottom: 1px solid #EEEFF0;

                .el-tree-node__content {
                    height: 52px;
                    display: flex;
                    align-items: center;
                }

                .el-tree-node__children {
                    .el-tree-node {
                        border-bottom: none !important;
                    }
                }
            }

            .el-tree-node:focus>.el-tree-node__content {
                background-color: transparent;
            }

            .is-current>.el-tree-node__content {
                background-color: #DDEAFF !important;
            }

            .el-tree-node__content:has(.custom-tree-node-active) {
                background-color: #DDEAFF !important;
            }

            .el-tree-node__content:has(.arrow-node) {
                .el-tree-node__expand-icon {
                    color: #a8abb2;
                    cursor: pointer;
                    visibility: visible;
                }
            }

            .is-current>.el-tree-node__content:has(.arrow-node, .file-node) {
                background-color: transparent !important;

                &:hover {
                    background-color: #eeeFF0 !important;
                }
            }

            .custom-tree-node {
                display: flex;
                height: 52px;
                align-items: center;
                position: relative;

                .file-icon {
                    width: 20px;
                    min-width: 20px;
                    height: 20px;
                    margin-right: 8px;
                }

                .label-content {
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;

                    .label {
                        color: #363B4C;
                        font-size: 14px;
                        @include SourceHanSansCN-Regular;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }
                }

                .custom-tree-arrow-box {
                    position: absolute;
                    left: -24px;
                    width: 24px;
                    height: 24px;
                }

                .custo-tree-loading {
                    position: absolute;
                    right: -10px;
                }
            }

            // .arrow-node{}
        }
    }

    .el-dialog__footer {
        padding: 0px !important;

        .know-footer {
            padding: 16px;
            box-sizing: border-box;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: end;
            border-top: 1px solid #EEEFF0;

            button {
                padding: 0px 15px !important;
            }
        }
    }
}
</style>